// pages/login/login.js
var app = getApp()
Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    // isHide: false,
    isHide: false,
    list: [],
    myuserInfo: null,
    allowISok: false,
    imgUrl: "",
    name: "",
    my_userID: "",
    my_openID: "",
    my_skey: "",
    user_existence_flag: 0,
    avatarUrl: "",
    nickName: "",
    city: "",
    gender: "",
    country: "",
    province: "",
    language: ""
  },

  onLoad: function (options) {
    var that = this;
    app.globalData.userId = wx.getStorageSync('key_userId')
    app.globalData.skey = wx.getStorageSync('key_skey')
    app.globalData.userInfo = wx.getStorageSync('key_userInfo')
    that.setData({
      my_userID: wx.getStorageSync('key_userId'),
      my_skey: wx.getStorageSync('key_skey'),
    })
    console.log("type_userId:", typeof (app.globalData.userId))
    console.log("初始获取缓存userId", app.globalData.userId)
    // console.log("初始获取缓存openID", app.globalData.openID)
    console.log("初始获取缓存skey", app.globalData.skey)
    console.log("初始获取缓存userInfo", app.globalData.userInfo)
    // 如果本地没有skey和userID，说明还没授权登录过；缓存得到的空数据是""
    if (app.globalData.skey != "" && app.globalData.userId != "") {
      //还需进一步判断，调用api查看该openID是否在该userid对应的用户记录中
      wx.request({
        // url: 'http://127.0.0.1:5000/api/user/checkUser', //本地项目api
        // url: 'http://8.136.195.245:5006/api/user/checkUser', //服务器
        url: 'http://8.136.195.245:8000/wechat/checkLoginState',
        data: {
          userId: app.globalData.userId,
          skey: app.globalData.skey
        },
        header: {
          "Content-Type": "application/json"
        },
        method: 'GET',
        dataType: 'json',
        success: function (res) {
          console.log(res)
          if (res.data.code == 200) {
            //用户存在且skey未过期
            console.log("skey和userid存在于本地缓存，且数据库存在对应的记录，不需要再授权登录,且更新了skey")
            console.log("userId", res.data.data.userId),
            console.log("skey", res.data.data.skey),
            app.globalData.userId = res.data.data.userId,
            app.globalData.skey = res.data.data.skey,
            //将数据存入缓存，更新skey。只要经常登录，登录状态就一直保持
            wx.setStorageSync('key_userId', res.data.data.userId),
            wx.setStorageSync('key_skey', res.data.data.skey),
            that.setData({
              //隐藏授权登录界面，修改显示参数，显示首页内容
              user_existence_flag: 1,
              allowISok: true,
              isHide: false,
            })
            wx.switchTab({
              url: '/pages/home/home'
            })
          }
          if (res.data.code == 400) {
            //用户不存在
            console.log("skey和userid存在于本地缓存，但数据库不存在对应的记录了或者skey过期，需要重新授权登录")
            that.setData({
              //隐藏授权登录界面，修改显示参数，显示首页内容
              user_existence_flag: 1,
              allowISok: true,
              isHide: true,
            })
          }
        },
        fail: function (err) {}, //请求失败
        complete: function () {} //请求完成后执行的函数
      }) //wx.request 结尾


    } //endif
    else {
      // 除了已经授权过并存储了openid和userid的正确情况，其他情况都需要授权登录
      //显示授权登录的界面，将参数设置为显现
      console.log("还没授权过，需要显示授权登录界面")
      that.setData({
        allowISok: true,
        isHide: true
      });
    }

  },
  getUserProfile(e) {
    var that1 = this;
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        console.log("用户点击了允许授权按钮：");
        console.log("res", res)
        console.log("使用getUserProfile获取的userinfo", res.userInfo)
        console.log("使用getUserProfile获取的userinfo.mickName", res.userInfo.nickName)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        //赋值给用户
        that1.data.gender = res.userInfo.gender;
        that1.data.nickName = res.userInfo.nickName;
        that1.data.avatarUrl = res.userInfo.avatarUrl;
        that1.data.country = res.userInfo.country;
        that1.data.province = res.userInfo.provicne;
        that1.data.city = res.userInfo.city;
        that1.data.language = res.userInfo.language;
        app.globalData.userInfo = res.userInfo;
        wx.setStorageSync('key_userInfo', res.userInfo)
        console.log("用户的nickName：" + that1.data.nickName);
        console.log("用户的avatarUrl：" + that1.data.avatarUrl);
        console.log("用户的city：" + that1.data.city);
        //使用wx.login方法获取code，此code几分钟内会失效再更新
        wx.login({
          success: resp => {
            console.log("用户的code：" + resp.code);
            that1.setData({
              allowISok: true
            })
            //参数齐全了，可以通过wx.request方法调用api从服务器得到openid和userid
            wx.request({
              // url: 'http://8.136.195.245:5006/api/wxlogin/login1', //服务器
              url: "http://8.136.195.245:8000/wechat/wxLogin",
              data: {
                code: resp.code,
                nickName: that1.data.nickName,
                avatarUrl: that1.data.avatarUrl,
                city: that1.data.city,
                province: that1.data.province,
                country: that1.data.country,
                gender: that1.data.gender,
                language: that1.data.language
              },
              header: {
                "Content-Type": "application/json"
              },
              method: 'POST',
              dataType: 'json',
              success: function (res) {
                console.log(res)
                app.globalData.userId = res.data.data.userId
                app.globalData.skey = res.data.data.skey
                console.log("userId", res.data.data.userId)
                console.log("skey", res.data.data.skey)
                //将数据存入缓存，sync同步保证了数据存好再继续，但有时候会导致请求api超时
                wx.setStorageSync('key_userId', res.data.data.userId)
                wx.setStorageSync('key_skey', res.data.data.skey)
                that1.setData({
                  //隐藏授权登录界面，修改显示参数，显示首页内容
                  allowISok: true,
                  isHide: false,
                  my_skey: res.data.data.skey,
                  my_userID: res.data.data.userId
                })
                wx.switchTab({
                  url: '/pages/home/home'
                })
                // wx.navigateTo({
                //   url: '/pages/index/index'
                // })

              },
              fail: function (err) {}, //请求失败
              complete: function () {} //请求完成后执行的函数
            })

          } //wx.request 结尾
        }) //login结尾
      },
      fail: res => {
        //拒绝授权
        var that = this;
        //用户按了拒绝按钮
        console.log("用户点击了拒绝授权按钮：");
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
          showCancel: false,
          confirmText: '返回授权',
          success: function (res) {
            // 用户没有授权成功，不需要改变 isHide 的值
            that.setData({
              allowISok: false
            });
            if (res.confirm) {
              console.log('用户点击了“返回授权”');
            }
          }
        });
        // return;
      }
    })
  },

  
})